package com.example.demo.controller;

import com.example.demo.pojo.ProductStar;
import com.example.demo.pojo.Response;
import com.example.demo.service.ProductStarService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/product_star")
@Tag(name = "商品点赞")
public class ProductStarController {
    @Autowired
    private ProductStarService productStarService;

    @Operation(summary = "商品点赞")
    @PostMapping("/star")
    @ApiResponse(responseCode = "200", description = "商品点赞成功", content = @Content(mediaType = "multipart/form-data"))
    public ResponseEntity<Response<ProductStar>> Star(@RequestParam("product_id") Integer product_id,
                                                      @RequestParam("user_id") Integer user_id) {
        Response<ProductStar> response = new Response<>();
        try {
            ProductStar productStar = productStarService.findByProductIdAndUserId(product_id, user_id);
            if (productStar == null) {
                productStarService.addStar(product_id, user_id);
                response.setMessage("点赞成功");
            } else {
                Boolean like_state = productStar.getLike_state();
                productStarService.changeLikeState(product_id, user_id, !like_state);
                response.setMessage("取消点赞");
            }
            response.setCode(200);

            response.setProductStar(productStarService.findByProductIdAndUserId(product_id, user_id));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
